from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from random import randint

from celery_tasks.sms.tasks import ccp_send_sms_code
from libs.yuntongxun.sms import CCP

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
from meiduo_mall.settings.dev import logger


class ImageCodeView(View):

    def get(self, request, uuid):
        text, image_code = captcha.generate_captcha()

        # 保存图片验证码

        redis_client = get_redis_connection('verify_image_code')
        redis_client.setex('img_%s' % uuid, 300, text)

        # 响应图片验证码
        return HttpResponse(image_code, content_type='imgae/jpeg')

class SMSCodeView(View):
    def get(self, request, mobile):
        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')

        # 2.校验图形验证码 如果正确 发送验证码, 不正确 直接返回
        # 2.1 根据uuid 去redis数据库查询 图片验证码

        # 如果有值 删除redis服务器上的图形验证码
        try:
            image_redis_client = get_redis_connection('verify_image_code')
            redis_img_code = image_redis_client.get('img_%s' % uuid)

            if redis_img_code is None:
                return JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'})
            # 千万注意: 在redis取出来的是 bytes 类型不能直接做对比 decode()
            if image_code.lower() != redis_img_code.decode().lower():
                return JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})

            image_redis_client.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 避免频繁发短信
        sms_redis_client = get_redis_connection('sms_code')
        send_flag = sms_redis_client.get('send_flag_%s' % mobile)

        if send_flag:
            return JsonResponse({'code': '4002', 'errmsg': '发送短信太频繁了'})
        # 3.生成短信验证码,redis-存储
        try:
            sms_code = "%06d" % randint(0, 999999)
            p1 = sms_redis_client.pipeline()
            p1.setex("send_flag_%s" % mobile, 60, 1)
            p1.setex("sms_%s" % mobile, 300, sms_code)
            p1.execute()
            print("当前验证码是:", sms_code)
        except Exception as e:
            logger.error(e)
        # 4.让第三方 容联云-给手机号-发送短信

        #                        手机号           验证码  过期时间5分钟 ,类型默认1
        #  CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        ccp_send_sms_code.delay(mobile, sms_code)


        # 5.告诉前端短信发送完毕
        return JsonResponse({'code': '0', 'errmsg': '发送短信成功'})